
# 安装python环境
# 安装playwright: pip install playwright
# 及浏览器: playwright install

from playwright.sync_api import sync_playwright


def get_list(browser,search_str):
    page = browser.new_page()
    page.goto(f'https://search.jd.com/Search?keyword={search_str}')
    li_list = page.query_selector_all('xpath=//*[@id="J_goodsList"]/ul/li')
    
    li_obj_list=[]
    for li in li_list:
        title = li.query_selector_all('xpath=//em')[1].inner_text()
        price = li.query_selector_all('xpath=//i')[0].inner_text()
        href = li.query_selector_all('xpath=//a')[0].get_attribute('href')
        obj={
            'title':title,
            'price':price,
            'href':href
        }  
        li_obj_list.append(obj)
    page.close()
    return li_obj_list
    

def main(search_str):
    with sync_playwright() as p:
        browser_type = p.chromium
        # browser = browser_type.launch(headless=False)
        browser = browser_type.launch(headless=True)
        lis = get_list(browser,search_str)
        print(lis)
        pass
    
if __name__ == '__main__':
    main('电脑')